# -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
if 'mailer' in settings.INSTALLED_APPS:
    from mailer import send_mail
else:
    from django.core.mail import send_mail


class EmailBaseForm(forms.Form):
    recipient_list = [mail_tuple[1] for mail_tuple in settings.MANAGERS]
    subject_template_name = 'contact_form/contact_subject.txt'
    template_name = 'contact_form/contact_body.html'

    def __init__(self, *args, **kwargs):
        if 'request' not in kwargs:
            raise TypeError('Keyword argument "request" must be supplied')
        request = kwargs.pop('request')
        super(EmailBaseForm, self).__init__(*args, **kwargs)
        self.request = request

    def get_message_dict(self):
        if not self.is_valid():
            raise ValueError('Message cannot be sent from invalid contact form')
        message_dict = {}
        for message_part in ('from_email', 'message', 'recipient_list', 'subject'):
            attr = getattr(self, message_part)
            message_dict[message_part] = callable(attr) and attr() or attr
        return message_dict

    _context = None
    def get_context(self):
        from django.contrib.sites.models import Site
        if not self.is_valid():
            raise ValueError('Cannot generate Context from invalid contact form')
        if self._context is None:
            context = dict(self.cleaned_data, site=Site.objects.get_current())
            self._context = RequestContext(self.request, context)
        return self._context
    
    def message(self):
        template_name = callable(self.template_name) and self.template_name() or self.template_name
        return render_to_string(template_name, self.get_context())

    def subject(self):
        subject = render_to_string(self.subject_template_name, self.get_context())
        return ''.join(subject.splitlines())

    def from_email(self):
        return settings.DEFAULT_FROM_EMAIL

    def save(self, fail_silently=False):
        """ Builds and sends the email message """
        send_mail(fail_silently=fail_silently, **self.get_message_dict())


class SimpleContactForm(EmailBaseForm):
    name = forms.CharField(max_length=100, label=_(u'Name'), widget=forms.TextInput())
    email = forms.EmailField(label=_(u'Email'))
    subject = forms.CharField(max_length=100, label=_(u'Subject'))
    body = forms.CharField(label=_(u'Message'), widget=forms.Textarea())
